﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using Microsoft.SharePoint;
using MSPE.Public.FOSS.AutoStatusPlus.Common;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.OperationHelpers;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.SPValidators;

namespace MSPE.Public.FOSS.AutoStatusPlus.StsAdm.Commands
{
    class AspSetLogOptions : SPOperation
    {
        #region Constructors
        /// <summary>
        /// Constructs a new instance of the <see cref="AspSetLogOptions" /> class.
        /// </summary>
        public AspSetLogOptions()
        {          
            SPParamCollection _parameters = new SPParamCollection
                                               {
                                                   new SPParam(GlobalConstants.UrlParamName, GlobalConstants.UrlParamName, true, null,
                                                               new SPUrlValidator(),
                                                               "Please specify the PWA site."),
                                                   new SPParam(GlobalConstants.LogFilePathParamName, GlobalConstants.LogFilePathParamName, false, null,
                                                               new ArrayList(){new SPNullOrNonEmptyValidator(), new SPDirectoryExistsValidator()}, 
                                                               "Please specify the path for the log file."),
                                                   new SPParam(GlobalConstants.LogFilePrefixParamName, GlobalConstants.LogFilePrefixParamName, false, null,
                                                               new SPNullOrNonEmptyValidator(),
                                                               "Please specify the prefix for the log file."),
                                                   new SPParam(GlobalConstants.NewLogFileEveryHourParamName, GlobalConstants.NewLogFileEveryHourParamName,
                                                               true, null, new SPTrueFalseValidator(), 
                                                               "Please specify whether to create a new log file every hour."),
                                                   new SPParam(GlobalConstants.LogTimesheetEventsKey, GlobalConstants.LogTimesheetEventsKey, true, null,
                                                               new SPTrueFalseValidator(), "Please specify whether to log timesheet events.")
                                               };

            StringBuilder _sb = new StringBuilder();
            _sb.AppendLine("-url <URL of PWA Site>");
            _sb.AppendLine("\t[-logfilepath] <Path to Log File>]");
            _sb.AppendLine("\t[-logfileprefix] <Prefix for Log File Name>");
            _sb.AppendLine("\t-newlogfileeveryhour <true | false>");
            _sb.AppendLine("\t-logtimesheetevents <true | false>");
            _sb.AppendLine();
            _sb.AppendLine();
            _sb.AppendLine("\tThis command is used to control the behavior of");
            _sb.AppendLine("\tAutoStatusPlus' log file.");
            _sb.AppendLine();
            _sb.AppendLine();
            _sb.AppendLine("The default setting for the logfilepath parameter is C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\12\\LOGS.");
            _sb.AppendLine("The default setting for the logfileprefix parameter is blank.");
            _sb.AppendLine("The newlogfileeveryhour and logtimesheetevents options are true by default.");

            Init(_parameters, _sb.ToString());
        } // AutoStatusPlusSetInterval()
        #endregion // Constructors

        #region Methods
        #region Overrides
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Gets the help message.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public override string GetHelpMessage(string command)
        {
            return HelpMessage;
        }

        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Run(string command, StringDictionary keyValues, out string output)
        {
            SPSite _site = null;
            SPWeb _pwaWeb = null;

            try
            {
                #region Read configuration settings from command line
                output = string.Empty;

                InitParameters(keyValues);

                // Read params into local fields
                string _url = Params[GlobalConstants.UrlParamName].Value.TrimEnd('/');
                string _logFilePath = Params[GlobalConstants.LogFilePathParamName].Value.TrimEnd('\\');
                string _logFilePrefix = Params[GlobalConstants.LogFilePrefixParamName].Value;
                string _newLogFileEveryHour = Params[GlobalConstants.NewLogFileEveryHourParamName].Value;
                string _logTimesheetEvents = Params[GlobalConstants.LogTimesheetEventsParamName].Value;
                #endregion // Read configuration settings from command line

                // This routine stores the settings in the PWA site's property bag
                _site = new SPSite(_url);

                if (_site.Url != _url)
                    throw new Exception("You may only configure Project Web Access Sites.");

                _pwaWeb = _site.RootWeb;

                if (_pwaWeb == null)
                    throw new Exception("Could not load the Site at the specified URL.");

                if (_pwaWeb.WebTemplateId != GlobalConstants.PwaSiteTemplateId)
                    throw new Exception("You may only configure Project Web Access Sites.");

                #region Load and update configuration settings
                Settings _loadedSettings = Settings.LoadSettings(_pwaWeb);
                
                if (!String.IsNullOrEmpty(_logFilePrefix))
                    _loadedSettings.LogFilePrefix = _logFilePrefix;

                if (!String.IsNullOrEmpty(_logFilePath))
                    _loadedSettings.LogFilePath = _logFilePath;

                _loadedSettings.NewLogFileEveryHour = Convert.ToBoolean(_newLogFileEveryHour);
                _loadedSettings.LogTimesheetEvents = Convert.ToBoolean(_logTimesheetEvents);

                Settings.UpdateSettings(_pwaWeb, _loadedSettings);
                #endregion // Load and update configuration settings

                // Use the ErrorCodes enum to return error codes: 
                // ErrorCodes.SyntaxError
                // ErrorCodes.GeneralError

                // Return 0 for success.
                return 0;
            }
            catch (Exception ex)
            {
                throw new Exception("Error encountered while setting event:\n\n" + ex.ToString());
            }

            finally
            {
                if (_pwaWeb != null) _pwaWeb.Dispose();

                if (_site != null) _site.Dispose();
            }
        }

        #endregion // Overrides
        #endregion // Methods
    }
}
